package com.cw.lang.common.framework.config;

import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;

import lombok.Data;

/**
 * @author chenwei
 * @version $$Id: FrameworkRpcProperties.java, v 0.1 2018/11/1 10:45 AM chenwei Exp $$
 */
@Data
@ConfigurationProperties("cw.framework")
public class FrameworkRpcProperties {

    private MvcProperties mvc = new MvcProperties();

    private RpcProperties rpc = new RpcProperties();

    /**
     * mvc相关配置参数
     */
    @Data
    public static class MvcProperties {

        /** 幂等校验超时时间，单位秒，默认120秒 */
        private int idempotentExpireTime = 120;

        private DefaultAdviceProperties defaultAdvice = new DefaultAdviceProperties();

        @Data
        public static class DefaultAdviceProperties {

            /** 是否启用Controller的异常advice */
            private Boolean enabled = true;
        }
    }

    @Data
    public static class RpcProperties {

        private ControllerLoggingAspectProperties controllerLoggingAspect = new ControllerLoggingAspectProperties();

        /** 都哪些http status作为超时异常 */
        private List<Integer> httpStatusAsTimeout = Lists.newArrayList(HttpStatus.REQUEST_TIMEOUT.value(),
            HttpStatus.GATEWAY_TIMEOUT.value());

        @Data
        public static class ControllerLoggingAspectProperties {

            /** 是否启用Controller的拦截器 */
            private Boolean enabled = true;
        }

        /**
         * 校验是否是超时异常
         *
         * @param httpStatus 入参httpStatus
         * @return true-是超时异常，false-不是超时异常
         */
        public boolean isTimeout(Integer httpStatus) {
            return !CollectionUtils.isEmpty(httpStatusAsTimeout) && httpStatusAsTimeout.stream()
                .anyMatch(httpStatus::equals);
        }
    }
}
